package org.budo.tencent.response;

import java.util.Map;

import org.budo.support.http.client.Response;
import org.budo.support.lang.util.NumberUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.support.servlet.util.QueryStringUtil;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * @author lmw
 */
public class TokenResponse extends AbstractResponse {
    private static final long serialVersionUID = -2364102915582135300L;

    private static final Logger log = Slf4j.getLogger();

    private String accessToken;

    private Integer expiresIn;

    public TokenResponse() {}

    public TokenResponse(Response response) {
        this.setResponse(response);

        String responseBody = response.getBody();
        Map<String, String[]> responseMap = QueryStringUtil.queryStringToMap(responseBody);

        String[] accessToken = responseMap.get("access_token");
        if (null == accessToken || accessToken.length < 1 || StringUtil.isEmpty(accessToken[0])) {
            log.error("#40 response=" + response.toSimpleString());
        } else {
            this.setAccessToken(accessToken[0]);

            String[] expiresInArray = responseMap.get("expires_in");
            String expiresInValue = expiresInArray[0];
            Integer expiresIn = NumberUtil.toInteger(expiresInValue);

            this.setExpiresIn(expiresIn);
        }
    }

    public String getAccessToken() {
        return this.accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public Integer getExpiresIn() {
        return this.expiresIn;
    }

    public void setExpiresIn(Integer expiresIn) {
        this.expiresIn = expiresIn;
    }

    @Override
    public String toString() {
        return super.toString() //
                + ", accessToken=" + this.getAccessToken() //
                + ", expiresIn=" + this.getExpiresIn();
    }
}